/*
* Copyright 2011 Pavel Kozhin 
*
* Licensed under the Apache License, Version 2.0 (the "License"); 
* you may not use this file except in compliance with the License. 
* You may obtain a copy of the License at 
* 
* http://www.apache.org/licenses/LICENSE-2.0
* 
* Unless required by applicable law or agreed to in writing, software 
* distributed  under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 
* See the License for the specific language governing permissions and 
* limitations under the License.
*
* Author: Pavel Kozhin.
*/
package org.etherframework.mediation.core
{
	import flash.utils.Dictionary;
	
	import org.etherframework.common.IDestroyable;

	public final class MediationHandlers implements IDestroyable
	{
		private var _map:Dictionary = new Dictionary();
		private var _uid:String;
		
		public function MediationHandlers(uid:String) 
		{
			_uid = uid;
		}
		
		public function getHandlers(id:String):Vector.<Function>
		{
			return _map[id];
		}
		
		public function addHandler(id:String, handler:Function):void
		{
			const items:Vector.<Function> = _map[id] || (_map[id] = new Vector.<Function>()); 
			
			items.push(handler);
		}
		
		public function removeHandler(id:String, handler:Function):void
		{
			const items:Vector.<Function> = _map[id];
			
			if (items)
			{
				for (var i:int = 0; i < items.length; i++) 
				{
					if (items[i] == handler)
					{
						items.splice(i, 1);
						break;
					}
				}
				
				if (!items.length)
					delete _map[id];
			}
		}
		
		public function hasHandlers(id:String):Boolean
		{
			return Boolean(_map[id]);
		}
		
		public function walk(visitor:Function):void
		{
			for (var uid:String in _map)
			{
				visitor(uid, _map[uid]);
			}
		}
		
		public function destroy():void
		{
			_map = null;
		}
	}
}